package com.example.jpetstoremanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.jpetstoremanager.persistence.AccountMapper;
import com.example.jpetstoremanager.persistence.SignOnMapper;
import com.example.jpetstoremanager.service.AccountService;
import org.apache.commons.codec.digest.DigestUtils;

import com.example.jpetstoremanager.entity.Account;
import com.example.jpetstoremanager.entity.SignOn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class AccountServiceImpl implements AccountService {


    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SignOnMapper signOnMapper;

    @Override
    public Account getAccount(String username) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",username);
        return accountMapper.selectOne(queryWrapper);
    }

    @Override
    public void insertAccount(Account account) {

//        //对密码进行加密
//        account.setPassword(DigestUtils.md5Hex(account.getPassword()));
        //在Account表中添加用户信息
        accountMapper.insert(account);

        //同时在signon表中添加用户信息
        SignOn signOn = new SignOn();
        signOn.setUsername(account.getUsername());
//        signOn.setPassword(account.getPassword());
        signOnMapper.insert(signOn);
    }
//
//    @Override
//    public void updateAccount(Account account) {
//        accountMapper.updateById(account);
//
//        SignOn signOn = new SignOn();
//        signOn.setUsername(account.getUsername());
//        signOn.setPassword(DigestUtils.md5Hex(account.getPassword()));
//
//        if (account.getPassword() != null && account.getPassword().length() > 0) {
//            signOnMapper.updateById(signOn);
//        }
//    }

    @Override
    public List<Account> findAllAccounts() {
        return accountMapper.selectList(null);
    }

    @Override
    public void deleteAccountById(int userid) {
        QueryWrapper<Account> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        Account account=accountMapper.selectOne(queryWrapper);
        QueryWrapper<SignOn> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("username",account.getUsername());
        signOnMapper.delete(queryWrapper1);
        accountMapper.delete(queryWrapper);
    }
}
